package com.fingard.dsp.bank.directbank.cpcn01;

import java.net.URLEncoder;

import com.fingard.crypto.SignVerifyHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.net.WebRequest;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

public class CPCN01Base extends DirectBase {
	protected String getCharset(){
		return getBankConfig().getCharset("UTF-8");
	}
	
	protected void writeCommonHeader(XmlTextWriter xmlWriter, CPCN01Header bankHeader) throws Exception{
		if(StringHelper.isNullOrEmpty(bankHeader.transCode)) {
			throw new Exception("transCode未初始化");
		}
		
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\" standalone=\"no\"?>");
		xmlWriter.writeStartElementByAttr("Request", "<Request version=\"2.1\">");
		xmlWriter.writeStartElement("Head");
	}
	
	protected String[] sendToBank(String p_for,String p_reqXml, ActSetItem actItem) throws Exception{
		String[] retStr = new String[]{"",""};
	
        WriteBankLogLn("提交银行的地址：" + bankFront.getUrl(p_for));
        
        String message = Base64Helper.getBase64(p_reqXml, getCharset());
        message = URLEncoder.encode(message, getCharset());
        
        StringBuilder tmpSb = new StringBuilder();
        
        byte[] bytesToSign = p_reqXml.getBytes(getCharset());
        byte[] signResult = SignVerifyHelper.signData(bytesToSign, "PKCS12", "SHA1withRSA", actItem.ownKeyStorePath,actItem.ownKeyPassword, tmpSb);
		String signature = toHexString(signResult);
		
		String p_reqStr = "message=" + message + "&signature=" + signature;
		
		if(signature !=null && tmpSb.length()==0){
//			WriteBankLogStep2(p_reqStr);
			
			WebRequest tmpWebRequest = new WebRequest(bankFront.getUrl(p_for));
			tmpWebRequest.setConnectTimeout(60000);
			tmpWebRequest.setRequestProperty("connection", "Close");
			
			byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
			retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
		}else {
			retStr[0] = FailCode.E9981;
			retStr[1] = "签名失败：" + tmpSb.toString();
		}
        
		return retStr;
	}
	
	/**
	 * 将byte[]转换为16进制字符串
	 */
	protected String toHexString(byte[] src) {
		StringBuilder hexString = new StringBuilder();  
		
	    if (src == null || src.length <= 0) {  
	        return null;  
	    }  
	    
	    for (int i = 0; i < src.length; i++) {  
	        int v = src[i] & 0xFF;  
	        String hv = Integer.toHexString(v);  
	        
	        if (hv.length() < 2) {  
	        	hexString.append(0);  
	        }  
	        
	        hexString.append(hv);  
	    }  
	    
		return hexString.toString();
	}
}
